package com.wuyou.sso.common.component;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * 本地资源服务器适配器
 *
 * @author lishangbu
 * @date 2021/7/3
 */
@Slf4j
public class LocalResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {

    @Autowired
    protected AuthenticationEntryPoint resourceAuthExceptionEntryPoint;

//    @Autowired
//    private PermitAllUrlProperties permitAllUrlProperties;

    @Autowired
    private TokenExtractor tokenExtractor;

    @Autowired
    private ResourceServerTokenServices resourceServerTokenServices;

    @Autowired
    private TokenStore tokenStore;

    /**
     * 默认的配置，对外暴露
     * modify at 20220322 添加token校验filter，用于自定义权限校验过程
     *
     * @param httpSecurity
     */
    @Override
    @SneakyThrows
    public void configure(HttpSecurity httpSecurity) {
        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        httpSecurity.headers().frameOptions().disable();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
                .authorizeRequests();
        // 配置对外暴露接口
//        permitAllUrlProperties.getIgnoreUrls().forEach(url -> registry.antMatchers(url).permitAll());
        registry.anyRequest().authenticated().and().csrf().disable();
                //.addFilterAfter(new CustomizedIDassTokenAuthenticationFilter(tokenStore, permitAllUrlProperties), LogoutFilter.class);

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint).tokenExtractor(tokenExtractor)
                .tokenServices(resourceServerTokenServices);
    }

}
